package com.zhitongyun.devlop.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.morgoo.droidplugin.pm.PluginManager;
import com.morgoo.helper.Log;
import com.zhitongyun.devlop.R;
import com.zhitongyun.devlop.net.HaleyPluginRequest;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    private TextView tvTest;
    private File[] plugins;

    private Activity context;
    String path;
    String packageName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        this.context = this;
        final TextView tvTest = (TextView) findViewById(R.id.tv_test);
        final ImageView imageView = (ImageView) findViewById(R.id.imageView);

        //获取插件
        File file = new File(Environment.getExternalStorageDirectory(), "/plugin");
        plugins = file.listFiles();
        //没有插件
        if (plugins == null || plugins.length == 0) {
            return;
        } else {//安装第一个插件
            path = plugins[0].getAbsolutePath();
            packageName = getPackageNameByApk(MainActivity.this, path);
            //1，安装，更新插件
            //PluginManager.getInstance().installPackage(plugins[0].getAbsolutePath(), 0);

            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    uninstallApk(packageName);
                    final String result = installApk(packageName, path);

                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, result, Toast.LENGTH_LONG).show();
                            tvTest.setText(plugins[0].getAbsolutePath() + result);
                        }
                    });
                }
            }).start();
        }


        Log.i("aa", path);

        Button btnTest = (Button) findViewById(R.id.btn_test);
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Drawable drawable = getApkIconByApk(MainActivity.this, path);

                String versionName = getVersionNameByApk(MainActivity.this, path);
                Toast.makeText(MainActivity.this, packageName + versionName, Toast.LENGTH_SHORT).show();
                imageView.setImageDrawable(drawable);
                startApk(packageName);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    /**
     * 安装插件apk
     *
     * @param apkFilePath
     */
//    public void installApk(String apkFilePath) {
//        try {
//            //如果apk已经安装要更新传PackageManagerCompat.INSTALL_REPLACE_EXISTING 否者传0
//            PluginManager.getInstance().installPackage(apkFilePath, PackageManagerCompat.INSTALL_REPLACE_EXISTING);
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 安装Apk, 耗时较长, 需要使用异步线程
     *
     * @param
     * @return [0:成功, 1:已安装, -1:连接失败, -2:权限不足, -3:安装失败]
     */
    public String installApk(String packageName, String apkFilePath) {
        if (!PluginManager.getInstance().isConnected()) {
            return "连接失败"; // 连接失败
        }

        if (isApkInstall(packageName)) {
            return "已安装"; // 已安装
        }

        try {
            int result = PluginManager.getInstance().installPackage(apkFilePath, 0);
            boolean isRequestPermission = (result == PluginManager.INSTALL_FAILED_NO_REQUESTEDPERMISSION);
            if (isRequestPermission) {//这里需要设置manifestmerger.enabled=true 确保2个版本一致
                return "权限不足";
            }
        } catch (RemoteException e) {
            e.printStackTrace();
            return "安装失败";
        }

        return "成功";
    }

    // Apk是否安装
    private boolean isApkInstall(String packageName) {
        PackageInfo info = null;
        try {
            info = PluginManager.getInstance().getPackageInfo(packageName, 0);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return info != null;
    }


    /**
     * 卸载插件apk
     *
     * @param packageName
     */
    public void uninstallApk(String packageName) {
        try {
            PluginManager.getInstance().deletePackage(packageName, 0);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动apk
     *
     * @param packageName
     */
    public void startApk(String packageName) {
        Log.i("aa", packageName);
        PackageManager pm = context.getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(packageName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public Drawable getApkIconByApk(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return appInfo.loadIcon(pm);
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String getPackageNameByApk(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            return info.packageName;
        }
        return null;
    }

    public String getVersionNameByApk(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            try {
                return info.versionName;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @OnClick(R.id.btn1)
    public void testNet() {
        HaleyPluginRequest.getAppCategory("",null);
    }

}
